package com.cskaoyan.udp.edition3.anotherperson;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
       接收发送方发送的数据
 */
public class ReceiverTask implements Runnable {

    DatagramSocket datagramSocket;

    public ReceiverTask(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        // 用于接收数据的数据报包
        byte[] bytes = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);

        boolean flag = true;

        try {
            while (flag) {
                // 接收发送端发送的数据
               datagramSocket.receive(receivePacket);

               // 解析接收到的数据
                byte[] data = receivePacket.getData();
                int offset = receivePacket.getOffset();
                int length = receivePacket.getLength();

                String result = new String(data, offset, length);
                // 获取发送方ip地址
                InetAddress address = receivePacket.getAddress();
                int port = receivePacket.getPort();
                System.out.println(address + "-" + port + ": " + result);

                if ("886".equals(result)) {
                    break;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 何时会执行到finally代码块? 当receiver接收到了886
            // 如果说我们还能保证，在执行datagramSocket.close()前，sender已经发送了886

            while (true) {
                synchronized (datagramSocket) {
                    if (AnotherPerson.senderOffline) {
                        // sender发出886
                        break;
                    }
                }


                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


            // 关闭socket
            datagramSocket.close();
        }


    }
}
